<template>
    <div>
        <el-container>
            <el-aside width="200px" style="height: 500px; display: flex" class="cab">
                <el-scrollbar style="height: 100%;width: 200px;">
                    <div>
                        <el-divider content-position="left">currUserName</el-divider>
                        <span style="color: #409EFF;">{{userName}}</span>
                    </div>
                    <div>
                        <el-divider content-position="left">在线的用户<i class="el-icon-refresh"
                                                                    @click="refreshOnlineUser"></i></el-divider>
                    </div>
                    <div v-show="onlineCount > 1">
                        <div v-for="item in onlineUserNames">
                            <el-button type="success" :key="item" @click="readyChat(item)"
                                       :disabled="currChatUserName === item">{{item}}
                            </el-button>
                            <el-divider/>
                        </div>
                    </div>
                    <div v-show="onlineCount <= 1">
                        <span style="color: #409EFF;">无其他用户在线</span>
                    </div>
                </el-scrollbar>
            </el-aside>
            <el-main>
                <el-header>当前 {{currChatUserName}}</el-header>
                <el-main class="cab">
                    <el-scrollbar class="chatlist" style="height:500px;" ref="myScrollbar">
                        <ul>
                            <template v-for="item in chatData">
                                <li class="chat-mine" v-if="item.sendUser===userName">
                                    <div class="chat-user">
                                        <el-avatar
                                                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                                    </div>
                                    <div class="time">
                                        <cite>
                                            <el-button type="text" style="padding: 0px">{{item.sendTime}}</el-button>
                                            {{item.sendUser}}
                                        </cite>
                                    </div>
                                    <div class="chat-text" v-html="item.content"></div>
                                </li>
                                <li v-if="item.sendUser===currChatUserName">
                                    <div class="chat-user">
                                        <el-avatar
                                                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                                    </div>
                                    <div class="time">
                                        <cite>
                                            {{item.sendUser}}
                                            <el-button type="text" style="padding: 0px">{{item.sendTime}}</el-button>
                                        </cite>
                                    </div>
                                    <div class="chat-text" v-html="item.content"></div>
                                </li>
                            </template>
                        </ul>
                    </el-scrollbar>

                </el-main>
                <el-footer>
                    <el-row :gutter="20">
                        <el-col :span="16" style="font-size: 17px">
                            <el-input
                                    type="textarea"
                                    placeholder="请输入内容"
                                    v-model="content"
                                    maxlength="50"
                                    show-word-limit
                                    style="width: 100%"
                                    @keyup.enter="sendMessage"></el-input>
                        </el-col>
                        <el-col :span="4" style="float: right">
                            <el-button @click="sendMessage" type="primary"><i class="el-icon-s-promotion
"></i></el-button>
                        </el-col>
                    </el-row>
                </el-footer>
            </el-main>
        </el-container>
    </div>
</template>

<script>
  import {addRecord, getIp, getRecord} from "@/api/chatrecord/chatrecord"

  export default {
    name: "index.vue",
    data() {
      return {
        // ws是否启动
        wsIsRun: false,
        // 定义ws对象
        webSocket: null,
        // ws请求链接（类似于ws后台地址）
        ws: '',
        // ws定时器
        wsTimer: null,
        //用户name
        userName: undefined,
        //在线的用户
        onlineUserNames: [],
        //在线人数
        onlineCount: undefined,
        //当前聊天用户
        currChatUserName: undefined,
        //当前聊天记录
        chatData: [],
        //发送内容
        content: undefined,
      }
    },
    async mounted() {
      getIp().then(response => {
        this.userName = response;
        this.wsIsRun = true;
        this.wsInit();
      });
    },
    updated: function () {
      this.scrollDown()
    },
    methods: {
      sendMessage() {
        if (this.isBlank(this.userName)) {
          this.$message.error("你掉线了!");
          return;
        }
        if (this.isBlank(this.currChatUserName)) {
          this.$message.error("都说了选人了你看不到是吗?");
          return;
        }
        if (this.onlineUserNames.indexOf(this.currChatUserName)) {
          this.$message.error("别人都下线了看不懂通知是吗?呜呜呜");
          return;
        }
        if (this.isBlank(this.content)) {
          return;
        }
        //添加到聊天记录
        let time = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
        this.chatData.push({
          sendUser: this.userName,
          receiveUser: this.currChatUserName,
          content: this.content,
          sendTime: time
        });
        //调用发送消息接口
        addRecord({
          sendUser: this.userName,
          receiveUser: this.currChatUserName,
          content: this.content
        }).then(response => {
          console.log("已发送消息并且入库");
        });
        //清空输入框
        this.content = undefined;
      },
      /**准备进行聊天*/
      readyChat(userName) {
        this.currChatUserName = userName;
        //查询和当前用户的聊天记录
        getRecord({sendUser: this.userName, receiveUser: this.currChatUserName}).then(response => {
          if (response.code === 200) {
            this.chatData.splice(0, this.chatData.length);
            if (response.data.length > 0) {
              response.data.forEach(item => {
                this.chatData.push(item);
              })
            }
          }
        })
      },
      refreshOnlineUser() {
        if (this.webSocket.readyState === 1) {
          this.$notify({
            title: '刷新当前在线用户',
            message: '已刷新',
            position: 'top-left'
          });
          this.webSocket.send('refresh')
        } else {
          this.$message.error("服务异常,正在重新连接");
          this.wsIsRun = true;
          this.wsInit();
        }
      },
      /**
       * 初始化ws
       */
      wsInit() {
        // const wsuri = `ws://localhost:8080/pirated/wechat/${this.userName}`
        const wsuri = `ws://39.106.212.69:9696/pirated/wechat/${this.userName}`
        this.ws = wsuri
        if (!this.wsIsRun) return
        // 销毁ws
        this.wsDestroy()
        // 初始化ws
        this.webSocket = new WebSocket(this.ws)
        // ws连接建立时触发
        this.webSocket.addEventListener('open', this.wsOpenHandler)
        // ws服务端给客户端推送消息
        this.webSocket.addEventListener('message', this.wsMessageHandler)
        // ws通信发生错误时触发
        this.webSocket.addEventListener('error', this.wsErrorHandler)
        // ws关闭时触发
        this.webSocket.addEventListener('close', this.wsCloseHandler)

        // 检查ws连接状态,readyState值为0表示尚未连接，1表示建立连接，2正在关闭连接，3已经关闭或无法打开
        clearInterval(this.wsTimer)
        this.wsTimer = setInterval(() => {
          if (this.webSocket.readyState === 1) {
            clearInterval(this.wsTimer)
          } else {
            console.log('ws建立连接失败')
            this.wsInit()
          }
        }, 3000)
      },
      wsOpenHandler(event) {
        this.$notify({
          title: '连接成功',
          message: `${this.userName}已连接`,
          type: 'success',
          offset: 100
        });
      },
      wsMessageHandler(e) {
        let d = JSON.parse(e.data);
        //系统通知
        if (d.messageType === 'notify_online' || d.messageType === 'notify_offline') {
          this.systemNotify(d);
        }
        //用户消息
        if (d.messageType === 'message') {
          this.userMessage(d);
        }
      },
      userMessage(d) {
        d.sendTime = this.parseTime(d.sendTime, '{y}-{m}-{d} {h}:{i}:{s}');
        //如果发送人不是当前正在聊的,就不显示,进行提示
        if (d.sendUser !== this.currChatUserName) {
          this.$notify({
            title: '接收到消息',
            message: `${d.sendUser}给你发了一条消息`,
            position: 'bottom-right'
          });
        } else {
          this.chatData.push(d);
        }
      },
      systemNotify(d) {
        //在线人数
        this.onlineCount = d.onlineCount;
        //用户列表
        if (d.onlineCount > 1) {
          this.onlineUserNames = d.userNames.split(",");
          let index = this.onlineUserNames.indexOf(this.userName);
          if (index !== -1) {
            this.onlineUserNames.splice(index, 1)
          }
        } else {
          this.onlineUserNames = [];
        }
        //通知上下线
        if (d.online !== this.userName && !this.isBlank(d.online)) {
          if (d.messageType === "notify_online") {
            this.$notify({
              title: '上线啦',
              message: `${d.online}上线啦`,
              position: 'bottom-right'
            });
          } else {
            this.$notify({
              title: '已下线',
              message: `${d.online}已下线`,
              position: 'bottom-right'
            });
          }
        }
      },
      /**
       * ws通信发生错误
       */
      wsErrorHandler(event) {
        console.log(event, '通信发生错误')
        this.wsInit()
      },
      /**
       * ws关闭
       */
      wsCloseHandler(event) {
        console.log(event, 'ws关闭')
        this.wsInit()
      },
      /**
       * 销毁ws
       */
      wsDestroy() {
        if (this.webSocket !== null) {
          this.webSocket.removeEventListener('open', this.wsOpenHandler)
          this.webSocket.removeEventListener('message', this.wsMessageHandler)
          this.webSocket.removeEventListener('error', this.wsErrorHandler)
          this.webSocket.removeEventListener('close', this.wsCloseHandler)
          this.webSocket.close()
          this.webSocket = null
          clearInterval(this.wsTimer)
        }
      },
      /**
       * 滚动条默认最下面
       */
      scrollDown() {
        this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
      },
      isBlank(value) {
        return (value === undefined || value === null || value.trim() === '');
      },
    },
  }
</script>

<style>
    .cab .is-horizontal {
        display: none;
    }

    .cab .el-scrollbar__wrap {
        overflow-x: hidden;
    }

    .chatlist ul .chat-mine {
        text-align: right;
        padding-left: 0;
        padding-right: 60px;
    }

    .chatlist ul li {
        position: relative;
        margin-bottom: 10px;
        padding-left: 60px;
        min-height: 68px;
        list-style: none;
    }

    .chat-mine .chat-user {
        left: auto;
        right: 3px;
    }

    .chat-user {
        position: absolute;
        left: 3px;
    }

    .chat-text,
    .chat-user {
        display: inline-block;
        vertical-align: top;
    }

    .chat-user img {
        width: 40px;
        height: 40px;
        border-radius: 100%;
    }

    .time {
        width: 100%;
    }

    cite {
        font-style: normal;
        line-height: 24px;
        font-size: 12px;
        white-space: nowrap;
        color: #999;
        text-align: left;
    }

    cite i {
        font-style: normal;
        padding-left: 5px;
        padding-right: 5px;
        font-size: 12px;
    }

    .chat-mine .chat-text {
        margin-left: 0;
        text-align: left;
        background-color: #33DF83;
        color: #fff;
    }

    .chat-text {
        position: relative;
        line-height: 22px;
        /*margin-top: 25px;*/
        padding: 10px 15px;
        background-color: #eee;
        border-radius: 3px;
        color: #333;
        word-break: break-all;
        max-width: 462px \9;
        max-width: 80%;
    }

    .chat-text,
    .chat-user {
        display: inline-block;
        vertical-align: top;
        font-size: 14px;
    }

    .chat-text:after {
        content: '';
        position: absolute;
        left: -10px;
        top: 15px;
        width: 0;
        height: 0;
        border-style: solid dashed dashed;
        border-color: #eee transparent transparent;
        overflow: hidden;
        border-width: 10px;
    }

    .chat-mine .chat-text:after {
        left: auto;
        right: -10px;
        border-top-color: #33DF83;
    }

</style>